package com.ruoyi.framework.config;

import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
@Slf4j
@RequiredArgsConstructor
public class WxAccessTokenManager {

    private String accessToken = null;

    @Value("${wx.appId}")
    private String appId;
    @Value("${wx.secret}")
    private String secret;

    private final RestTemplate restTemplate;

    private final ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();


    public String getAccessToken(){
        String ret;
        ReentrantReadWriteLock.ReadLock readLock = reentrantReadWriteLock.readLock();
        try{
            readLock.lock();
            ret = accessToken;
        }
        finally {
            readLock.unlock();
        }
        return ret;
    }

    public void updateAccessToken(String accessToken){
        ReentrantReadWriteLock.WriteLock writeLock = reentrantReadWriteLock.writeLock();
        try{
            writeLock.lock();
            this.accessToken = accessToken;
        }
        finally {
            writeLock.unlock();
        }
    }

    /**
     * 获取微信accessToken
     */
    @Scheduled(cron = "0 0 * * * ?")
    public void refreshToken() {
        String accessToken;
        try {
            String url =
                    String.format(
                            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                            appId,
                            secret);
            JSONObject body = restTemplate.getForEntity(url, JSONObject.class).getBody();
            if (!Objects.isNull(body)){
                log.info("获取accessToken返回内容:"+body.toJSONString());
                accessToken = (String) body.get("access_token");
                updateAccessToken(accessToken);
            }
        } catch (Exception e) {
            log.error("调用获取微信accessToken接口出错：", e);
        }
    }
}
